<template>
  <el-dialog :title="dialog.title" :visible.sync="dialog.show" width="600px" custom-class="mydialog" append-to-body @close="handleClose">
    <div class="dialog-content">
      <el-form ref="form1" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="申请仓：" >
          <el-select v-model="form.warehouse" placeholder="选择仓库" class="seach-select" size="small">
            <el-option v-for="item in form.warehouse_options" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商：" >
          <el-select v-model="form.supplier" placeholder="选择供应商" class="seach-select" size="small" @change="findSku()">
            <el-option v-for="item in form.supplier_options" :key="item.supplierId" :label="item.supplierName" :value="item.supplierId"/>
          </el-select>
        </el-form-item>
        <el-table
          :data="tableData"
          border
          show-summary
          style="width: 100%"
          class="dialog-table">
          <el-table-column
            label="操作"
            fixed="left"
            width="100">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-plus"
                type="text"
                size="small"
                @click.native.prevent="addRow(scope.$index+1)"
              />
              <el-button
                icon="el-icon-delete"
                type="text"
                size="small"
                @click.native.prevent="deleteRow(scope.$index, tableData)"/>
            </template>
          </el-table-column>
          <el-table-column property="skuName" label="SKU名称">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.skuName"
                :remote-method="remoteMethod"
                :loading="loading"
                filterable
                remote
                reserve-keyword
                placeholder="输入sku名称"
                @change="changeSku(scope.row.skuName)"
              >
                <el-option
                  v-for="item in options"
                  :key="item"
                  :label="item.skuName"
                  :value="item.skuName"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column property="amount" label="采购数量">
            <template slot-scope="scope">
              <el-input v-model="scope.row.amount" class="cnt-class"/>
            </template>
          </el-table-column>
        </el-table>

      </el-form>
      <div class="text-center mt-30">
        <el-button class="greenbt" type="primary" @click="submitBut()">保存</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import { skuList, queryWarehouseList, querySupplierList, createEditPurchaseOrder } from '@/api/pas/purchase'
export default{
  props: {
    modalStaticData: {
      type: Object,
      default: () => {}
    },
    // 父组件调用时传进来的参数
    modalData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      dialog: {
        title: '', show: true
      },
      form: {
        warehouse_options: [], warehouse: '', supplier_options: [], supplier: '', supplierId: ''
      },
      rules: {},
      tableData: [{
        skuId: '',
        skuCode: '',
        skuName: '',
        amount: '1',
        warehouseId: '',
        supplierId: '',
        purchaseId: ''
      }
      ],
      options: [],
      purchaseId: ''
    }
  },
  mounted() {
    this.getWarehouseList()
    this.getSupplierList()
    this.purchaseId = this.modalData[0].purchaseId
    // 初始化编辑页面
    this.tableData = this.modalData
    // for (let index = 0; index < this.tableData.length; index++) {
    //  this.tableData[index].amount = this.tableData[index].amount
    // }
    this.form.warehouse = this.tableData[0].warehouseId
    this.form.supplier = this.tableData[0].supplier
    this.form.supplierId = this.tableData[0].supplierId
    this.getSkuList(this.form.supplierId)
  },
  methods: {
    handleClose() {
      this.$emit('close')
    },
    deleteRow(index, rows) {
      rows.splice(index, 1)
    },
    addRow(index) {
      var dTable = 'table' + index
      dTable = { skuId: '', skuCode: '', skuName: '', amount: '1' }
      this.tableData.push(dTable)
    },
    // 保存
    submitBut() {
      if (isNaN(this.form.supplier)) {
        this.form.supplier = this.form.supplierId
      }
      for (let index = 0; index < this.tableData.length; index++) {
        if (this.tableData[index].skuName === null || this.tableData[index].skuName === '') {
          this.$message('请选择sku！')
          return
        }
        if (this.tableData[index].amount === '0' || this.tableData[index].amount === null || this.tableData[index].amount === '') {
          this.$message('采购量不能为0或空！')
          return
        }
        if (isNaN(this.tableData[index].amount)) {
          this.$message('采购量必须是数字！')
          return
        }
        if (parseInt(this.tableData[index].amount) < 0) {
          this.$message('采购量必须是正整数！')
          return
        }
        var num = this.tableData[index].amount + ''
        if (num.indexOf('.') !== -1) {
          this.$message('采购量必须是整数！')
          return
        }
        this.tableData[index].purchaseNum = this.tableData[index].amount
        this.tableData[index].warehouseId = this.form.warehouse
        this.tableData[index].supplierId = this.form.supplier
        this.tableData[index].purchaseId = this.purchaseId
      }
      var data = {
        param: JSON.stringify(this.tableData)
      }
      createEditPurchaseOrder(data)
        .then(response => {
          if (response.data.status === 'success') {
            this.$message({
              type: 'success',
              message: '编辑成功!'
            })
            this.handleClose()
          } else {
            this.options = []
          }
        }).finally(() => {
          this.modalStaticData.closeChildAndRefresh()
        })
    },
    // 供应商筛选sku
    findSku() {
      this.getSkuList(this.form.supplier)
      this.tableData = [{
        skuId: '',
        skuCode: '',
        skuName: '',
        amount: '1',
        warehouseId: '',
        supplierId: ''
      }
      ]
    },
    changeSku(value) {
      // 当前选择行
      // 远程获取的参数 options
      for (let index = 0; index < this.options.length; index++) {
        if (this.options[index].skuName === value) {
          var skuName = this.options[index].skuName
          var skuId = this.options[index].skuId
          for (let index = 0; index < this.tableData.length; index++) {
            if (this.tableData[index].skuName === value) {
              this.tableData[index].skuName = skuName
              this.tableData[index].skuId = skuId
            }
          }
        }
      }
    },
    // 仓库
    getWarehouseList(supplierId) {
      var data = {
        supplierId: supplierId
      }
      queryWarehouseList(data)
        .then(response => {
          if (response.data.status === 'success') {
            this.form.warehouse_options = response.data.data.list
          } else {
            this.options = []
          }
        }).catch(error => {
          this.$message({
            message: '查询仓库失败',
            type: 'warning'
          })
          this.listLoading = false
          console.log(error)
        })
    },
    // 供应商
    getSupplierList(query) {
      var data = {
        search: query
      }
      querySupplierList(data)
        .then(response => {
          if (response.data.status === 'success') {
            this.form.supplier_options = response.data.data.supplierList
          } else {
            this.options = []
          }
        }).catch(error => {
          this.$message({
            message: '查询供应商失败',
            type: 'warning'
          })
          this.listLoading = false
          console.log(error)
        })
    },
    // sku
    getSkuList(query) {
      var data = {
        supplierId: query
      }
      skuList(data)
        .then(response => {
          if (response.data.status === 'success') {
            this.options = response.data.data.skuList
          } else {
            this.options = []
          }
        })
        .catch(error => {
          this.$message({
            message: '查询sku失败',
            type: 'warning'
          })
          this.listLoading = false
          console.log(error)
        })
    }

  }
}
</script>
